﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Business.UI.Controls
{
    /// <summary>
    /// ScreenUnlock.xaml 的交互逻辑
    /// </summary>
    public partial class WordLink : UserControl
    {

        Line currentLine;

        /// <summary>
        /// 当前WordGroup
        /// </summary>
        WordGroup CurrentWordGroup;

        #region 圆点大小
        /// <summary>
        /// 圆点的大小
        /// </summary>
        public static readonly DependencyProperty PointSizeProperty = DependencyProperty.Register("PointSize", typeof(int), typeof(WordLink), new FrameworkPropertyMetadata(30));

        /// <summary>
        /// 九宫格圆点的大小
        /// </summary>
        public int PointSize { get { return Convert.ToInt32(GetValue(PointSizeProperty)); } set { SetValue(PointSizeProperty, value); } }
        #endregion

        #region 当前级别
        /// <summary>
        /// 当前级别
        /// </summary>
        public static readonly DependencyProperty LevelProperty = DependencyProperty.Register("Level", typeof(int), typeof(WordLink), new FrameworkPropertyMetadata(0));

        /// <summary>
        /// 当前级别,最小级别是0
        /// </summary>
        public int Level
        {
            get { return Convert.ToInt32(GetValue(LevelProperty)); }
            set
            {
                SetValue(LevelProperty, value);
                ScreenUnlock_Loaded(null, null);
            }
        }
        #endregion

        #region 词组集合
        /// <summary>
        /// 词组集合
        /// </summary>
        public static readonly DependencyProperty WordGroupsProperty = DependencyProperty.Register("WordGroups", typeof(List<WordGroup>), typeof(WordLink));

        /// <summary>
        /// 词组集合
        /// </summary>
        public List<WordGroup> WordGroups { get { return (List<WordGroup>)(GetValue(WordGroupsProperty)); } set { SetValue(WordGroupsProperty, value); } }
        #endregion

        #region 正确的个数
        /// <summary>
        /// 正确的个数
        /// </summary>
        public static readonly DependencyProperty RightCountProperty = DependencyProperty.Register("RightCount", typeof(int), typeof(WordLink));

        /// <summary>
        /// 正确的个数
        /// </summary>
        public int RightCount { get { return Convert.ToInt32(GetValue(RightCountProperty)); } set { SetValue(RightCountProperty, value); } }
        #endregion


        #region 文本宽度
        /// <summary>
        /// 当前级别
        /// </summary>
        public static readonly DependencyProperty WordWithProperty = DependencyProperty.Register("WordWith", typeof(int), typeof(WordLink), new FrameworkPropertyMetadata(150));

        /// <summary>
        /// 当前级别
        /// </summary>
        public int WordWith { get { return Convert.ToInt32(GetValue(WordWithProperty)); } set { SetValue(WordWithProperty, value); } }
        #endregion

        #region 圆点颜色
        public static readonly DependencyProperty ColorProperty = DependencyProperty.Register("Color", typeof(SolidColorBrush), typeof(WordLink));

        /// <summary>
        /// 圆点颜色
        /// </summary>
        public SolidColorBrush Color
        {
            get { return GetValue(ColorProperty) as SolidColorBrush; }
            set { SetValue(ColorProperty, value); }
        }
        #endregion

        readonly List<LineExt> Lines = new List<LineExt>();
        LineExt currentlineext;
        /// <summary>
        /// 构造函数
        /// </summary>
        public WordLink()
        {
            InitializeComponent();
            this.Loaded += ScreenUnlock_Loaded;
            this.MouseDown += ScreenUnlock_MouseDown;
            this.MouseUp += ScreenUnlock_MouseUp;
            this.MouseMove += ScreenUnlock_MouseMove;
        }

        /// <summary>
        /// 重做
        /// </summary>
        public void Refreash()
        {
            ScreenUnlock_Loaded(null, null);
        }

        /// <summary>
        /// 鼠标左键弹起
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScreenUnlock_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var point = e.GetPosition(this);
            if (VisualTreeHelper.HitTest(this, point).VisualHit is Ellipse ellipse) //鼠标经过圆点
            {
                //该点是左侧点
                if (!Lines.Select(p => p.LeftEllipse).Contains(ellipse) && (ellipse.Tag as EllTag).Loaciton == "1" && currentlineext.RightEllipse != null)
                {
                    currentlineext.LeftEllipse = ellipse;
                    Lines.Add(currentlineext);
                }
                //该点是右侧点
                else if (!Lines.Select(p => p.RightEllipse).Contains(ellipse) && (ellipse.Tag as EllTag).Loaciton == "2" && currentlineext.LeftEllipse != null)
                {
                    currentlineext.RightEllipse = ellipse;
                    Lines.Add(currentlineext);
                }
                else
                {
                    canvas.Children.Remove(currentLine);
                }
            }
            else
            {
                canvas.Children.Remove(currentLine);
            }
            currentLine = null;
            RightCount = Lines == null ? 0 : Lines.Count(p => p.Right);
        }

        /// <summary>
        /// 鼠标移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScreenUnlock_MouseMove(object sender, MouseEventArgs e)
        {
            //鼠标左键处于点击状态
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                //获取当前鼠标位置
                var point = e.GetPosition(this);

                ///当没有遇到圆点之前绘制跟随鼠标的线
                if (currentLine != null)
                {
                    canvas.Children.Remove(currentLine);
                    currentLine.X2 = point.X + 2;
                    currentLine.Y2 = point.Y + 2;
                    canvas.Children.Add(currentLine);
                }

                //线跟着移动
                if (VisualTreeHelper.HitTest(this, point).VisualHit is Ellipse ellipse)
                {
                    point = (ellipse.Tag as EllTag).Point;
                    canvas.Children.Remove(currentLine);
                    if (currentLine == null)
                        return;
                    currentLine.X2 = point.X + 1;
                    currentLine.Y2 = point.Y + 1;
                    (ellipse.Tag as EllTag).Line = currentLine;
                    canvas.Children.Add(currentLine);
                }
            }
        }

        /// <summary>
        /// 鼠标点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScreenUnlock_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                //获取当前鼠标位置
                var point = e.GetPosition(this);
                //鼠标所在位置是否有圆点
                if (VisualTreeHelper.HitTest(this, point).VisualHit is Ellipse ellipse) //鼠标经过圆点
                {
                    currentlineext = null;
                    //判断该点是否已经有线
                    if ((ellipse.Tag as EllTag).Line != null)
                    {
                        canvas.Children.Remove((ellipse.Tag as EllTag).Line);
                        //同时需要删除Lines中的元素
                        if ((ellipse.Tag as EllTag).Loaciton == "1")
                        {
                            var t = Lines.Where(q => q.LeftEllipse == ellipse).FirstOrDefault();
                            Lines.Remove(t);
                        }
                        else
                        {
                            var t = Lines.Where(tt => tt.RightEllipse == ellipse).FirstOrDefault();
                            Lines.Remove(t);
                        }
                    }
                    if ((ellipse.Tag as EllTag).Loaciton == "1")
                        currentlineext = new LineExt() { LeftEllipse = ellipse };
                    else
                        currentlineext = new LineExt() { RightEllipse = ellipse };
                    var p = (ellipse.Tag as EllTag).Point;
                    currentLine = new Line()
                    {
                        Stroke = Color,
                        StrokeThickness = PointSize / 2,
                        X1 = p.X,
                        Y1 = p.Y,
                        X2 = p.X,
                        Y2 = p.Y
                    };
                    canvas.Children.Add(currentLine);
                }
                else if (VisualTreeHelper.HitTest(this, point).VisualHit is Line line) //如果是线，则删除
                {
                    canvas.Children.Remove(line);
                    //删除LInes中的元素


                }
            }
        }

        /// <summary>
        /// Load事件,绘制九宫格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScreenUnlock_Loaded(object sender, RoutedEventArgs e)
        {
            if (WordGroups != null && WordGroups.Count > 0)
            {
                CurrentWordGroup = WordGroups[Level];
                InitCan(CurrentWordGroup);
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="currentWordGroup"></param>
        private void InitCan(WordGroup wordGroup)
        {
            canvas.Children.Clear();
            Lines.Clear();
            int space = (int)this.canvas.ActualHeight / wordGroup.Words.Count;
            var words = wordGroup.Words.Select(p => p.OptionWord).ToList();
            words = RandomSortList(words);

            for (int i = 0; i < wordGroup.Words.Count; i++)
            {
                int y = (space - PointSize) / 2 + space * i;
                //左侧
                var textblock = new TextBlock()
                {
                    Height = PointSize,
                    Width = WordWith,
                    Text = words[i],
                    FontSize = PointSize - 5
                };
                Canvas.SetLeft(textblock, 0);
                Canvas.SetTop(textblock, y);
                canvas.Children.Add(textblock);

                var ellipse = new Ellipse()
                {
                    Height = PointSize,
                    Width = PointSize,
                    Stroke = Color,
                    StrokeThickness = PointSize,
                    Tag = new EllTag { Loaciton = "1", Point = new Point(WordWith + PointSize / 2, y + PointSize / 2), Word = words[i] }
                };
                Canvas.SetLeft(ellipse, textblock.Width);
                Canvas.SetTop(ellipse, y);
                canvas.Children.Add(ellipse);

                //右侧
                textblock = new TextBlock()
                {
                    Height = PointSize,
                    Width = WordWith,
                    Text = wordGroup.Words[i].VisibleWord,
                    FontSize = PointSize - 5,
                };
                Canvas.SetLeft(textblock, this.canvas.ActualWidth - WordWith);
                Canvas.SetTop(textblock, y);
                canvas.Children.Add(textblock);

                ellipse = new Ellipse()
                {
                    Height = PointSize,
                    Width = PointSize,
                    Stroke = Color,
                    StrokeThickness = PointSize,
                    Tag = new EllTag { Loaciton = "2", Point = new Point(this.canvas.ActualWidth - PointSize / 2 - WordWith, y + PointSize / 2), Word = wordGroup.Words[i].OptionWord }
                };
                Canvas.SetLeft(ellipse, this.canvas.ActualWidth - PointSize - WordWith);
                Canvas.SetTop(ellipse, y);
                canvas.Children.Add(ellipse);

            }
        }

        /// <summary>
        /// 随机排序
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ListT"></param>
        /// <returns></returns>
        List<T> RandomSortList<T>(List<T> ListT)
        {
            Random random = new Random();
            List<T> newList = new List<T>();
            foreach (T item in ListT)
            {
                newList.Insert(random.Next(newList.Count + 1), item);
            }
            return newList;
        }



    }

    /// <summary>
    /// 点的Ｔａｇ
    /// </summary>
    internal class EllTag
    {
        /// <summary>
        /// 1:左侧,2右侧
        /// </summary>
        public string Loaciton { get; set; }

        /// <summary>
        /// 词
        /// </summary>
        public string Word { get; set; }

        /// <summary>
        /// Line
        /// </summary>
        public Line Line { get; set; }

        /// <summary>
        /// 中心点位置
        /// </summary>
        public Point Point { get; set; }

    }

    /// <summary>
    /// 连线定义
    /// </summary>
    internal class LineExt
    {
        /// <summary>
        /// 左侧点
        /// </summary>

        public Ellipse LeftEllipse { get; set; }

        /// <summary>
        /// 右侧点
        /// </summary>
        public Ellipse RightEllipse { get; set; }

        /// <summary>
        /// 正确
        /// </summary>
        public bool Right
        {
            get
            {
                return LeftEllipse != null && RightEllipse != null && (LeftEllipse.Tag as EllTag).Word == (RightEllipse.Tag as EllTag).Word;
            }
        }
    }
    /// <summary>
    /// 词组
    /// </summary>
    public class WordGroup
    {
        /// <summary>
        /// 词组
        /// </summary>
        public List<Word> Words { get; set; }

        /// <summary>
        /// 时间
        /// </summary>
        public long Time { get; set; }
    }

    /// <summary>
    /// 一个词
    /// </summary>
    public class Word
    {
        public Word(string word)
        {
            AllWord = word;
        }

        /// <summary>
        /// 原始词组
        /// </summary>
        public string AllWord { get; set; }

        /// <summary>
        /// 展示的词
        /// </summary>
        public string VisibleWord
        {
            get
            {
                string tt = "";
                for (int i = 0; i < OptionWord.Length; i++)
                {
                    tt += "  ";
                }
                return AllWord.Replace(OptionWord, tt);
            }
        }

        /// <summary>
        /// 选择的词
        /// </summary>
        public string OptionWord
        {
            get
            {
                int arr = AllWord.IndexOf(")") - 1 - AllWord.IndexOf("(");//结束位置 减 1 再减 开始位置 获取中间位置数
                if (arr == 0)
                {

                }
                return AllWord.Substring(AllWord.IndexOf("(") + 1, arr);//参数1：开始位置加1 参数2：长度：中间位置数
            }
        }

    }
}
